package demo06

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"log"
)

type Person struct {
	Name  string
	Phone string
	Email string
	Age   int
	Other string
}

// https://juejin.cn/post/7220035506990071865?searchId=20241119152350E7FFD396F9872302CF04
// go基于协程对100w数据量的excel写与读

// go get github.com/360EntSecGroup-Skylar/excelize/v2@v2.3.0

func ReadWriteDemo() {
	execlPath := "test5.xlsx"
	persons := []Person{
		{Name: "Tom", Phone: "13888888888", Email: "tom@example.com", Age: 20, Other: "other"},
		{Name: "Jerry", Phone: "13999999999", Email: "jerry@example.com", Age: 22, Other: "other"},
	}
	// 新建一个工作簿（excel 文件）
	file := excelize.NewFile()

	// 新建一个 Sheet，命名为 Sheet1
	sheetName := "Sheet12"
	sheet := file.NewSheet(sheetName)

	// 写入字段属性行，从 A1 开始
	file.SetCellValue(sheetName, "A1", "name")
	file.SetCellValue(sheetName, "B1", "phone")
	file.SetCellValue(sheetName, "C1", "email")
	file.SetCellValue(sheetName, "D1", "age")
	file.SetCellValue(sheetName, "E1", "other")

	// 写入数据行
	rowIndex := 2 // 第二行开始
	for _, person := range persons {
		file.SetCellValue(sheetName, "A"+fmt.Sprint(rowIndex), person.Name)
		file.SetCellValue(sheetName, "B"+fmt.Sprint(rowIndex), person.Phone)
		file.SetCellValue(sheetName, "C"+fmt.Sprint(rowIndex), person.Email)
		file.SetCellValue(sheetName, "D"+fmt.Sprint(rowIndex), person.Age)
		file.SetCellValue(sheetName, "E"+fmt.Sprint(rowIndex), person.Other)
		rowIndex++
	}

	// 设置生成的 Excel 文件的默认 Sheet
	file.SetActiveSheet(sheet)

	// 保存 Excel 文件
	err := file.SaveAs(execlPath)
	if err != nil {
		log.Fatal(err)
		//panic(err)
	}

	log.Panicln("ok")
}
